package com.fang.dao;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanListHandler;

import com.fang.entity.Category;
import com.fang.entity.Goods;
import com.fang.utils.JDBCUtils;
import com.mysql.jdbc.StringUtils;

public class GoodsDao {

	public List<Category> querycategory() {
		QueryRunner qr = new QueryRunner(JDBCUtils.getDataSource());
		String sql = "select * from category";
		try {
			return qr.query(sql, new BeanListHandler<Category>(Category.class));
		} catch (Exception e) {
			e.printStackTrace();
			throw new RuntimeException("查询分类失败" + e);
		}
	}

	public List<Goods> querygoods(Goods goods) {
		
			QueryRunner qr = new QueryRunner(JDBCUtils.getDataSource());
			String sql = "select * from goods where 1=1 ";
			List<Object> con = new ArrayList<Object>();
			List<Goods> list=null;
			// 商品id，适用于商品的详情
			if (goods.getId() != null && goods.getId() != 0) {
				sql = sql + " and id=? ";
				con.add(goods.getId());
			}
			// 根据名称查询，模糊查询
			if(org.apache.commons.lang3.StringUtils.isNoneBlank(goods.getName())){
				sql=sql+" and name like ? ";
				con.add("%"+goods.getName()+"%");
			}
			// 根据类别查询
			if (goods.getCid() != null && goods.getCid() != 0) {
				sql = sql + " and cid=? ";
				con.add(goods.getCid());
			}
		try {
			 list = qr.query(sql, new BeanListHandler<Goods>(Goods.class),
					con.toArray());
		} catch (Exception e) {
			e.printStackTrace();
			throw new RuntimeException("查询商品失败"+e);
		}
		return list;
	}

}
